package ossadaptor

import (
	"encoding/json"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common/utils"
	"os"
	"path"
	"strings"
	"time"
)

type LocalOss struct {
	bindDomain  string
	storagePath string
	subPath     string
}

func NewLocalOss(bindDomain string, path string) *LocalOss {
	if !strings.HasPrefix(bindDomain, "http") {
		bindDomain = "http://" + bindDomain
	}
	return &LocalOss{
		bindDomain:  bindDomain,
		storagePath: path,
		subPath:     "oss",
	}
}

func (oss *LocalOss) String() (string, error) {
	bts, err := json.Marshal(oss)
	if err != nil {
		return "", err
	}
	return string(bts), nil
}

func (oss *LocalOss) Parse(s string) error {
	err := json.Unmarshal([]byte(s), oss)
	if err != nil {
		return err
	}
	return nil
}

func renameFileName() string {
	return utils.Md5Sum(time.Now().Format(time.DateTime) + utils.RandFigureCode(6))
}

func (oss *LocalOss) ossStoragePath() string {
	p := path.Join(oss.storagePath, oss.subPath)
	if !utils.IsExistPath(p) {
		os.MkdirAll(p, os.ModeDir|0755)
	}
	return p
}

func (oss *LocalOss) url(fName string) string {
	return fmt.Sprintf("%s/%s/%s", oss.bindDomain, oss.subPath, fName)
}

func (oss *LocalOss) Put(file string, objName string) (*UploadRet, error) {
	ret := &UploadRet{}

	fPath := path.Join(oss.ossStoragePath(), objName)

	err := os.Rename(file, fPath)
	if err != nil {
		return ret, err
	}

	ret.Url = oss.url(objName)

	return ret, nil
}
